package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.admin.WemediaConstants;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    /*
     * 首页list
     * */
    @Value("${file.oss.web-site}")
    private String webSite;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        dto.checkParam();
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.<WmNews>lambdaQuery();
        //1. 如果有文章标题，按照文章标题模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            wrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        //2. 如果有频道信息，按照频道ID查询
        if (dto.getChannelId() != null) {
            wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //3. 如果有文章状态，按照状态信息进行查询
        if (dto.getStatus() != null) {
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //4. 如果开始时间，结束时间不为空按照时间区间查询
        if (dto.getBeginPubDate() != null) {
            wrapper.ge(WmNews::getPublishTime, dto.getBeginPubDate());
        }
        if (dto.getEndPubDate() != null) {
            wrapper.le(WmNews::getPublishTime, dto.getEndPubDate());
        }
        //5. 按照登录用户ID去查询
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        wrapper.eq(WmNews::getUserId, user.getId());
        //6. 按照创建时间降序
        wrapper.orderByDesc(WmNews::getCreatedTime);
        //7. 分页查询，返回结果设置host  地址 为图片访问前缀
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmNews> pageResult = page(page, wrapper);
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal(), pageResult.getRecords());
        result.setHost(webSite);
        return result;
    }


    @Autowired
    RabbitTemplate rabbitTemplate;
    //自媒体文章发布
    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {

        WmNews wmNews = getWmNews(dto);
        //2.保存或修改文章
        saveOrUpdateWmNews(wmNews);
        if(WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(dto.getStatus())){
            return ResponseResult.okResult();
        }
        //3. 保存文章和素材的关联关系
        //3.1 从文章中抽取出所有的素材路径
        List<String> materiaUrls = parseContentImages(dto.getContent());
        //3.2保存文章内容 所引用的素材 关联关系
        if (!CollectionUtils.isEmpty(materiaUrls)) {
            saveRelativeInfo(materiaUrls, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);
        }

        //3.3 保存文章封面 所引用的素材 关联关系

        saveRelativeInfoForCover(dto,materiaUrls,wmNews);


        //自动审核文章消息
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        log.info("成功发送文章自动审核消息，当前待审核的文章id==>{}",wmNews.getId());
        // 特殊情况 type =-1 代表自动生成封面
        return ResponseResult.okResult();
    }


/*
        保存封面和素材的关联关系
                如果type=-1 需要根据内容素材 生成封面列表
* */
    private void saveRelativeInfoForCover(WmNewsDTO dto, List<String> materiaUrls, WmNews wmNews) {
        List<String> images = dto.getImages();
        if(WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            int size = materiaUrls == null ? 0 : materiaUrls.size();
            if (size > 0 && size < 2) {
                images = materiaUrls.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            } else if (size > 2) {
                images = materiaUrls.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            } else {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

            wmNews.setImages(imagesToStr(images));
            updateById(wmNews);
        }
        //保存封面和素材的关系
        if (CollectionUtils.isEmpty(images)) {
            images=images.stream().map(url->url.replaceAll(webSite,"")).collect(Collectors.toList());

            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_IMAGE_REFERENCE);

        }
    }

    /*
     * 保存
     * */
    private void saveRelativeInfo(List<String> materiaUrls, Integer newsId, Short type) {
        //1. 先根据素材路径列表和当前登陆用户ID 查询出素材id集合
        /*List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(
                Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materiaUrls)
                        .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
                        .select(WmMaterial::getId));*/
        List<Integer> materialIds=wmMaterialMapper.selectRelationsIds(materiaUrls,WmThreadLocalUtils.getUser().getId());

        //2.判断传入路径的数量和素材id的素材是否一致，如果不一致说明素材缺失
        //if (materiaUrls.size() != wmMaterials.size()) {
        if (materiaUrls.size() != materialIds.size()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"素材缺失，保存失败");
        }
        //3.将素材id 文章id 引用类型  插入到关联表中
      /*  for (WmMaterial wmMaterial : wmMaterials) {
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();

            wmNewsMaterial.setMaterialId(wmMaterial.getId());
            wmNewsMaterial.setNewsId(newsId);
            wmNewsMaterial.setType(type);
            wmNewsMaterialMapper.insert(wmNewsMaterial);*/

            wmNewsMaterialMapper.saveRelations(materialIds,newsId,type);
        }


    /*
     *获取素材路径
     * */
    private List<String> parseContentImages(String content) {
        List<Map> mapList = JSON.parseArray(content, Map.class);
        return mapList.stream()
                .filter(m -> WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(m.get("type")))
                .map(m -> String.valueOf(m.get("value")))
                .map(u -> u.replaceAll(webSite, ""))
                .distinct()
                .collect(Collectors.toList());
    }

    private void saveOrUpdateWmNews(WmNews wmNews) {

        //如果有文章id就修改，没有就保存
        if (wmNews.getId() == null) {
            save(wmNews);
        } else {
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }

    }

    private WmNews getWmNews(WmNewsDTO dto) {
//1. 将dto封装成wmNews对象
        //      参数校验（content title 是否登录）
        if (StringUtils.isBlank(dto.getContent()) || StringUtils.isBlank(dto.getTitle())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "标题或内容不能为空");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }
        wmNews.setImages(imagesToStr(dto.getImages()));
        wmNews.setUserId(user.getId());
        wmNews.setCreatedTime(new Date());
//        wmNews.setPublishTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);
        return wmNews;

    }

    private String imagesToStr(List<String> images) {
        if (CollectionUtils.isEmpty(images)) {
            return null;
        }
        return images.stream()
                .map(url -> url.replaceAll(webSite, ""))
                .collect(Collectors.joining(","));//收集拼接用,隔开
    }

    /**
     * 根据文章id查询文章
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1 参数检查
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }
/*
删除
 */

    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if(id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        if(wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }
        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult();
    }
/*
* 上下架
* */
    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {

        if(dto==null || dto.getId()==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Short enable = dto.getEnable();
        if(!WemediaConstants.WM_NEWS_UP.equals(enable)&&!WemediaConstants.WM_NEWS_DOWN.equals(enable)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"上下架状态错误");
        }
        WmNews wmNews = getById(dto.getId());
        if(wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (!wmNews.getStatus().equals(WemediaConstants.WM_NEWS_PUBLISH_STATUS)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
        }
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()));

        if (WemediaConstants.WM_NEWS_UP.equals(enable)) {
            rabbitTemplate.convertAndSend(
                    NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                    NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,
                    wmNews.getArticleId()
            );
            log.info("成功，发送文章上架的消息，消息内容：{}",wmNews.getArticleId());
        }else {
            rabbitTemplate.convertAndSend(
                    NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                    NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,
                    wmNews.getArticleId()
            );
            log.info("成功，发送文章下架的消息，消息内容：{}",wmNews.getArticleId());
        }


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    @Autowired
    WmNewsMapper wmNewsMapper;
    /**
     * 查询文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        //1.检查参数
        dto.checkParam();
        //记录当前页
        int currentPage = dto.getPage();
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());

        if(StringUtils.isNotBlank(dto.getTitle())){
            //  concat(%,?,%)
            dto.setTitle("%"+dto.getTitle()+"%");
        }

        //2.分页查询
        List<WmNewsVO> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        long count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        ResponseResult result = new PageResponseResult(currentPage, dto.getSize(), count, wmNewsVoList);
        result.setHost(webSite);
        return result;
    }


    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Autowired
    private WmUserMapper wmUserMapper;
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if(wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }

        //4.封装vo信息返回
        WmNewsVO wmNewsVo = new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }

    /**
     * 自媒体文章人工审核
     * @param status 2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        //1.参数检查
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 检查文章状态 不能为9  已发布
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已发布");
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);

        if(WemediaConstants.WM_NEWS_AUTH_PASS.equals(status)){
            long publishTime =wmNews.getPublishTime().getTime();
            long nowTime =System.currentTimeMillis();
            long remainTime=publishTime-nowTime;
            //5.2 发送消息 并设置延迟时间
            rabbitTemplate.convertAndSend(
                    PublishArticleConstants.DELAY_DIRECT_EXCHANGE,
                    PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY,
                    wmNews.getId(),
                    new MessagePostProcessor() {
                        @Override
                        public Message postProcessMessage(Message message) throws AmqpException {
                            //设置x-delay延迟时间
                            message.getMessageProperties().setHeader("x-delay",remainTime<=0 ? 0:remainTime);
                            return message;
                        }
                    }
            );
            log.info("成功发送延时发布文章消息 文章id:{},延迟时间：{}"+wmNews.getId(),remainTime);
        }

        // TODO 通知定时发布文章
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
